package com.devbobcorn.misaka.client;

import com.devbobcorn.misaka.Misaka;

import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map.Entry;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import net.minecraft.client.Minecraft;
import net.minecraft.util.RegistryKey;
import net.minecraft.util.registry.MutableRegistry;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.biome.Biome;

import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.ClientChatEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;

@EventBusSubscriber(modid = Misaka.MODID, bus = EventBusSubscriber.Bus.FORGE, value = Dist.CLIENT)
public class ClientForgeEventSubscriber {
    @SuppressWarnings({ "resource", "null" })
    @SubscribeEvent
    public static void onClientChat(ClientChatEvent event) {
            if (event.getMessage().toLowerCase().contains("exportbiomes")) {
                MutableRegistry<Biome> reg = Minecraft.getInstance().level.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY);
            
            final File exportFile = new File(Minecraft.getInstance().gameDirectory, "biomes.json");

            try {
                Gson gson = new GsonBuilder().setPrettyPrinting().create();
                HashMap<Integer, String> dict = new HashMap<>();

                // Short-circuit logic here...
                if (exportFile.exists() || exportFile.createNewFile())
                {
                    for (Entry<RegistryKey<Biome>,Biome> biome : reg.entrySet()) {
                        dict.put(reg.getId(biome.getValue()), biome.getValue().getRegistryName().toString());
                    }

                    FileWriter writer = new FileWriter(exportFile);
                    writer.write(gson.toJson(dict));
                    writer.close();
                    Minecraft.getInstance().player.displayClientMessage(new StringTextComponent("Successfully exported biomes.").withStyle(TextFormatting.GREEN), true);
                }

            } catch (Exception e) {
                Minecraft.getInstance().player.displayClientMessage(new StringTextComponent("Failed to export biomes.").withStyle(TextFormatting.RED), true);
            }
        }
    }
}
